/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.proof;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.photo.ThumbnailControl;
import cn.ac.nercis.pes.community.constant.SaveMethod;
import cn.ac.nercis.pes.community.constant.ThumbnailSize;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.proof.ProofView;
import cn.ac.nercis.pes.model.dto.evaluation.content.proof.GradingDTO;
import cn.ac.nercis.pes.service.evaluation.ProofService;
import cn.ac.nercis.pes.service.utils.FileManage;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 系统定级匹配证明管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class GradingController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private TextField nameTxt;
    @FXML
    private DatePicker datePicker;
    @FXML
    private VBox scanFilePictureBox;
    @FXML
    private Button addScanFilePictureBtn;

    private final ProofService proofService;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);
    private String currentSystemId;

    public GradingController() {
        this.proofService = SpringUtils.getBean(ProofService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        addScanFilePictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));

        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerDateChange(this.datePicker);
        realTimeSaveManager.listenerTextChange(this.nameTxt);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化系统定级匹配证明信息...");
        this.currentSystemId = systemId;
        loadGrading();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        saveGrading(SaveMethod.SAVE, false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        saveGrading(SaveMethod.SAVE, false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        saveGrading(SaveMethod.SAVE, true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        saveGrading(SaveMethod.SAVE_NOW,false);
    }

    @FXML
    private void onAddScanFilePictureClick(){
        LogUtils.info(log, "执行信息系统安全等级保护备案证明添加图片操作...");
        if(scanFilePictureBox.getChildren().size()>0){
            AlertDialog alertDialog = AlertDialog.builder()
                    .withMode(AlertMode.CONFIRM)
                    .withType(AlertType.WARN)
                    .withTitle("操作提示")
                    .withContent("当前已存在信息系统安全等级保护备案证明，继续操作将进行覆盖！")
                    .withContainer(this.page)
                    .build();
            alertDialog.show((confirm)->{
                if(!confirm){
                    return;
                }
                addPicture();
            });
        }else{
            addPicture();
        }
    }

    private String getPicture(VBox pictureBox){
        return pictureBox.getChildren()
                .stream()
                .filter(n->n instanceof ThumbnailControl)
                .map(n->(ThumbnailControl)n)
                .map(ThumbnailControl::getPictureFile)
                .map(File::getName)
                .findFirst()
                .orElse("");
    }

    private void addPicture(){
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择信息系统安全等级保护备案证明图片文件");
        fileChooser.getExtensionFilters().addAll(ControlUtils.getImageExtensionFilters());
        var currentSystem = AppStore.getCurrentSystem(this.currentSystemId);
        File selectFile = fileChooser.showOpenDialog(Objects.requireNonNull(currentSystem).getEvaluationStage());
        if(Objects.isNull(selectFile)){
            return;
        }
        try {
            File pictureFile = storePictureFile(selectFile);
            loadThumbnailPicture(pictureFile.getName());
            saveGrading(SaveMethod.SAVE_NOW,false);
        }catch (IOException ex){
            log.error("添加信息系统安全等级保护备案证明图片文件出错：",ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN)
                    .withMessage("添加信息系统安全等级保护备案证明图片文件失败！")
                    .build().show();
        }
    }

    protected void onRenameFileChick(ThumbnailControl source, String oldValue, String newValue) {
        LogUtils.info(log, "执行图片文件重命名操作...");
        if (StringUtils.isBlank(newValue)) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("图片文件名不能为空！")
                    .build().show();
            return;
        }
        if (StringUtils.equals(oldValue, newValue)) {
            source.setEditMode(false);
            return;
        }
        String newFileName = newValue.concat(FileManage.getFileSuffix(source.getPictureFile().getName()));
        boolean result = source.renamePhotoFile(newFileName);
        if (!result) {
            source.renamePhotoFile(oldValue);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL)
                    .withMessage("图片文件重命名失败！")
                    .build().show();
            return;
        }
        source.setEditMode(false);
        saveGrading(SaveMethod.SAVE_NOW, false);
    }

    private void onDeleteClick(ThumbnailControl source){
        LogUtils.info(log, "执行信息系统安全等级保护备案证明图片文件删除操作...");
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("是否删除当前信息系统安全等级保护备案证明图片文件？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            scanFilePictureBox.getChildren().remove(source);
            removeStoreFile(source.getPictureFile());
            saveGrading(SaveMethod.SAVE_NOW,false);
            //显示添加图片按钮
            addScanFilePictureBtn.setVisible(true);
        });
    }

    private void removeStoreFile(@NonNull File file){
        try {
            FileUtils.delete(file);
        }catch (IOException ex){
            log.error(String.format("删除%s图文件失败：",file.getName()),ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("移除图文件失败")
                    .build().show();
        }
    }

    private File storePictureFile(@NonNull File file) throws IOException {
        File saveFile = FileUtils.getFile(FileManage.getGradingDir(this.currentSystemId),file.getName());
        FileManage.copyFile(file,saveFile);
        return saveFile;
    }

    private void loadGrading() {
        LogUtils.info(log, "获取信息系统安全等级保护备案证明信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        //清空页面旧的图片
        CompletableFuture.supplyAsync(() -> this.proofService.findGrading(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    nameTxt.setText(res.getName());
                    datePicker.setValue(res.getDate());
                    loadThumbnailPicture(res.getScanFile());
                }))
                .exceptionally((ex) -> {
                    log.error("获取信息系统安全等级保护备案证明信息出错!", ex);
                    return null;
                });
    }

    private void saveGrading(SaveMethod saveMethod, boolean finish) {
        var grading = GradingDTO.builder()
                .name(this.nameTxt.getText())
                .date(this.datePicker.getValue())
                .scanFile(getPicture(this.scanFilePictureBox))
                .build();
        LogUtils.info(log, "保存信息系统安全等级保护备案证明信息...");
        LogUtils.record(log, "请求数据：systemId:{},data:{}", this.currentSystemId, grading);
        CompletableFuture.supplyAsync(() -> this.proofService.saveGrading(this.currentSystemId, grading))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishProcess(finish);
                        if (saveMethod == SaveMethod.SAVE) {
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                    } else {
                        if(saveMethod == SaveMethod.SAVE_NOW){
                            log.error("即时保存失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存信息系统安全等级保护备案证明信息出错!", ex);
                    return null;
                });
    }

    private void loadThumbnailPicture(String pictureName){
        if(StringUtils.isBlank(pictureName)){
            return;
        }
        File pictureFile = FileUtils.getFile(FileManage.getGradingDir(this.currentSystemId),pictureName);
        if(!pictureFile.exists()){
            return;
        }
        try {
            ThumbnailControl thumbnailControl = new ThumbnailControl(pictureFile,this.page, ThumbnailSize.NORMAL_X4);
            thumbnailControl.setOnRenameEvent(this::onRenameFileChick);
            thumbnailControl.setOnDeleteEvent(this::onDeleteClick);
            scanFilePictureBox.getChildren().add(thumbnailControl);
            //隐藏添加图片按钮
            addScanFilePictureBtn.setVisible(false);
        } catch (IOException ex) {
            log.error("加载信息系统安全等级保护备案证明图片文件失败：", ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL)
                    .withMessage("载入信息系统安全等级保护备案证明图片文件失败")
                    .build().show();
        }
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, ProofView.class);
        if(prepareView.getController() instanceof ProofController controller){
            controller.setEvalProcess(EvaluationModule.PROOF_GRADING, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }
}